const multer = require('multer')
const mkdirp = require('mkdirp')
const moment = require('moment')
const path = require('path')

// 封装保存上传文件功能
const upload = () => {
  // 获取当前的日期
  const nowDate = moment().format('YYYY-MM-DD')
  const storage = multer.diskStorage({
    destination: async (req, file, cb) => {
      // 指定上传后保存到哪一个文件夹中
      await mkdirp(`./static/upload/${nowDate}`) // 创建目录
      cb(null, `static/upload/${nowDate}`) //
    },
    filename: (req, file, cb) => {
      // 给保存的文件命名
      let extname = path.extname(file.originalname) // 获取后缀名

      let fileName = path.parse(file.originalname).name // 获取上传的文件名
      // cb(null,`${fileName}-${Date.now()}${extname}`)
      cb(null, `${Date.now()}${extname}`)
    }
  })

  return multer({ storage })
}
/**
 * 封装多条件查询
 * @param {a:1,b:2} newObj 传递的对象
 * @returns  where a='1' and b='2'
 */
const getCondition = (newObj) => {
  const arr = []
  for (let key in newObj) {
    arr.push(`${key}='${newObj[key]}'`)
  }
  const condition = ' where ' + arr.join(' and ')
  return condition
}

module.exports = {
  upload,
  getCondition
}
